﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Net;
using System.Net.Mail;
using KishOnlineDataAccess;
using KishOnlineCommone;
using System.Configuration;
using System.IO;

namespace KishOnlineDomain.Common
{
    public class Utility
    {
        const string AuthenticatedSession = "AuthenticatedSession";
        public static KishOnlineDataAccess.KishOnlineDataContext GetDataContext()
        {
            KishOnlineDataAccess.KishOnlineDataContext client = new KishOnlineDataAccess.
                KishOnlineDataContext(Static.ConnectionString);
            return client;
        }

        public static ResultDTO SendEmail(ContactMessage emailToSend)
        {
            ResultDTO result = new ResultDTO();
                     var fromAddress = new MailAddress(ConfigurationManager.AppSettings["EMailAddress"], ConfigurationManager.AppSettings["EMailDisplayTitle"]);
            string fromPassword = ConfigurationManager.AppSettings["EMailPassword"];
            string senderEmail =  (string.IsNullOrEmpty(emailToSend.senderEmail)? "</br>Sender Email is " + emailToSend.senderEmail:"");
            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(ConfigurationManager.AppSettings["EMailAddress"], fromPassword);
            MailMessage message = new MailMessage();
            smtpClient.Host = ConfigurationManager.AppSettings["MailHost"]; //"mail.f2co.ir";
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;
            message.From = fromAddress;
            message.Subject = emailToSend.subject; ;
            //Set IsBodyHtml to true means you can send HTML email.
            message.IsBodyHtml = true;
            message.Body = emailToSend.body + senderEmail;
            message.To.Add(emailToSend.to);
            try
            {
                smtpClient.Send(message);
                result.IsSucceed = true;
                result.Message = new MessageDTO() { Code = 15, Type = MessageType.Event };
            }
            catch
            {
                result.IsSucceed = false;
                result.Message = new MessageDTO() { Code = 30, Type = MessageType.Error };
            }
            return result;
        }

        public static bool IsAuthenticatedUser()
        {
            object LogginSession = System.Web.HttpContext.Current.Session[AuthenticatedSession];
            bool result =  (LogginSession != null) && (LogginSession is bool) && ((bool)LogginSession  == true);
            return result;
        }

        public static ResultDTO logError(Exception ex,int MessageCode, string ExceptionLocation)
        {
            ResultDTO result = new ResultDTO();
            result.IsSucceed = false;
            result.Message = MessageReader.Get(MessageType.Error, MessageCode);
            using (var db = Common.Utility.GetDataContext())
            {
                var log = new LogError() { Message = ex.Message, Location = ExceptionLocation };
                db.LogErrors.InsertOnSubmit(log);
                db.SubmitChanges();
            }
            return result;
        }
        public static void logError(Exception ex, string ExceptionLocation)
        {           
            using (var db = Common.Utility.GetDataContext())
            {
                var log = new LogError() { Message = ex.Message, Location = ExceptionLocation };
                db.LogErrors.InsertOnSubmit(log);
                db.SubmitChanges();
            }
        }
        public static void SetLogginSession(UserDTO User)
        {
           System.Web.HttpContext.Current.Session["User"] = User;
        }

        public static UserDTO GetLogginSession()
        {
            if (System.Web.HttpContext.Current != null && (System.Web.HttpContext.Current.Session["User"] is UserDTO))
            {
                return System.Web.HttpContext.Current.Session["User"] as UserDTO;
            }
            else
            {
                return null;
            }


            //UserDTO User = new UserDTO
            //{
            //    ID = 12,
            //    Roles = new System.Collections.Generic.List<RoleTypes> { RoleTypes.Memebr },
            //    Email = "ho_faraji@yahoo.com",
            //    FirstName = "Hossein",
            //    LastName = "Faraji",
            //    Password = "123456",
            //    DateCreated = DateTime.Now.Date,
            //    strDateCreated = DateTime.Now.Date.ToShortDateString(),
            //    IsDeleted = false,
            //    IsActive = true,
            //    Telephone = "1234567",
            //    Address = "Tehran"
            //};
            //return User;
        }

        public static string UploadFile()
        {
            string photoPath = "";
            var page = new System.Web.UI.Page();
            bool addedSuccecfully = Convert.ToBoolean(page.Session["IsSucceed"]);

            if (addedSuccecfully)
            {
                string picName = (page.Session["picName"] as List<string>)[0];
                if (!string.IsNullOrEmpty(picName))
                {
                    //copy picture file from temp to product image folder
                    string imgFolder = page.Server.MapPath(ConfigurationManager.AppSettings["ImgFolder"]);
                    string imgPath = System.IO.Path.Combine(imgFolder, picName);
                    if (!System.IO.Directory.Exists(imgFolder))
                    {
                        MakeDir(imgFolder);
                    }
                    string tempFolder = page.Server.MapPath(ConfigurationManager.AppSettings["tempFolder"]);
                    string tempPath = Path.Combine(tempFolder, picName);
                    System.IO.File.Copy(tempPath, imgPath);
                    System.IO.File.Delete(tempPath);
                    //photoPath = "../ProductImages" + "/" + picName;
                    photoPath = ConfigurationManager.AppSettings["ImgFolder"] + "/" + picName;

                }
            }
            page.Session.Remove("IsSucceed");
            page.Session.Remove("picName");
            return photoPath;
        }
        public static List<string> UploadFiles()
        {
            List<string> photosPath = new List<string>();
            var page = new System.Web.UI.Page();
            bool addedSuccecfully = Convert.ToBoolean(page.Session["IsSucceed"]);

            if (addedSuccecfully && page.Session["picName"] != null && (page.Session["picName"] is List<string> ) )
            {
                List<string> picNames = page.Session["picName"] as List<string>;
                foreach (string picName in picNames)
                {
                    if (!string.IsNullOrEmpty(picName))
                    {
                        //copy picture file from temp to product image folder
                        string imgFolder = page.Server.MapPath(ConfigurationManager.AppSettings["ImgFolder"]);
                        string imgPath = System.IO.Path.Combine(imgFolder, picName);
                        if (!System.IO.Directory.Exists(imgFolder))
                        {
                            MakeDir(imgFolder);
                        }
                        string tempFolder = page.Server.MapPath(ConfigurationManager.AppSettings["tempFolder"]);
                        string tempPath = Path.Combine(tempFolder, picName);
                        System.IO.File.Copy(tempPath, imgPath);
                        System.IO.File.Delete(tempPath);
                        photosPath.Add(ConfigurationManager.AppSettings["ImgFolder"] + "/" + picName);
                    }
                }
            }
            page.Session.Remove("IsSucceed");
            page.Session.Remove("picName");
            return photosPath;
        }
        private static string MakeDir(string path)
        {
            return Directory.CreateDirectory(path).FullName;
        }
    }

    public abstract class ImageRemover
    {
        public abstract ResultDTO DeleteImage(long ImageID);
        public static ImageRemover GetImageRemover(ImageType type)
        {
            ImageRemover ConcreatClass = null;
            switch (type)
            {
                case ImageType.ImageCar:
                    ConcreatClass = new RemoveImageCar();
                    break;
            }
            return ConcreatClass;
        }
    }
    public enum ImageType
    {
        ImageCar
    }
    public class RemoveImageCar:ImageRemover
    {
        public override ResultDTO DeleteImage(long ImageID)
        {
            try
            {
                string imgFolder = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
                using (var db = KishOnlineDomain.Common.Utility.GetDataContext())
                {
                    var image = db.Files.Where(q => q.ID.Equals(ImageID)).SingleOrDefault();
                    var Carimage = db.CarImages.Where(q => q.FileID.Equals(ImageID)).FirstOrDefault();
                    db.Files.DeleteOnSubmit(image);
                    db.CarImages.DeleteOnSubmit(Carimage);
                    Carimage.IsDeleted = true;
                    string imgPath = System.IO.Path.Combine(imgFolder, image.Path.Replace('/', '\\').Remove(0, 2));
                    System.IO.File.Delete(imgPath);
                    db.SubmitChanges();
                }
                return new ResultDTO { IsSucceed = true, Message = MessageReader.Get(MessageType.Event, 19) };
            }
            catch (Exception ex)
            {
                return Utility.logError(ex, 35, System.Reflection.MethodInfo.GetCurrentMethod().ReflectedType.FullName);
            }
        }
    }
}
